package com.firebird.app.fekpsl.ui.activity.exam

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.firebird.app.fekpsl.R
import com.firebird.app.fekpsl.adapter.exam.BlankFillingQuestionAdapter
import com.firebird.app.fekpsl.adapter.exam.MultipleAnswerAdapter
import com.firebird.app.fekpsl.adapter.exam.SingleAnswerAdapter
import com.firebird.app.fekpsl.adapter.exam.TrueFalseQuestionAdapter
import com.firebird.app.fekpsl.base.BaseMvpSwipeBackActivity
import com.firebird.app.fekpsl.bean.BlankFillingQuestion
import com.firebird.app.fekpsl.bean.MultipleAnswer
import com.firebird.app.fekpsl.bean.SingleAnswer
import com.firebird.app.fekpsl.bean.TrueFalseQuestion
import com.firebird.app.fekpsl.constant.Constant
import com.firebird.app.fekpsl.ext.showToast
import com.firebird.app.fekpsl.mvp.exam.ExamContract
import com.firebird.app.fekpsl.mvp.exam.ExamPresenter
import com.firebird.app.fekpsl.utils.ImageLoader
import com.firebird.app.fekpsl.widget.SpaceItemDecoration
import com.mylhyl.circledialog.BaseCircleDialog
import com.mylhyl.circledialog.CircleDialog
import kotlinx.android.synthetic.main.exam_paper.*
import java.sql.Date
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*


class ExamActivity :  BaseMvpSwipeBackActivity<ExamContract.View, ExamContract.Presenter>(),ExamContract.View {
    private var pf_examSubjectId=0
    private var startTime_format=""
    private var endTime_format=""

    private var dialogFragment: BaseCircleDialog? = null

    companion object {
        fun start(context: Context?, examSubjectId: Int, examUserName: String, examUserAvatar: String,examPaperName: String, bundle: Bundle? = null) {
            Intent(context, ExamActivity::class.java).run {
                putExtra(Constant.EXAM_SUBJECT_ID_KEY, examSubjectId)
                putExtra(Constant.EXAM_USER_NAME_KEY, examUserName)
                putExtra(Constant.EXAM_USER_AVATAR_KEY, examUserAvatar)
                putExtra(Constant.EXAM_PAPER_NAME_KEY, examPaperName)
                context?.startActivity(this, bundle)
            }
        }
    }

    /**
     * RecyclerView Divider
     */
    private val recyclerViewItemDecoration by lazy {
        SpaceItemDecoration(this)
    }

    private val singleAnswerAdapter: SingleAnswerAdapter by lazy {
        SingleAnswerAdapter()
    }
    private val multipleAnswerAdapter: MultipleAnswerAdapter by lazy {
        MultipleAnswerAdapter()
    }
    private val trueFalseQuestionAdapter: TrueFalseQuestionAdapter by lazy {
        TrueFalseQuestionAdapter()
    }
    private val blankFillingQuestionAdapter: BlankFillingQuestionAdapter by lazy {
        BlankFillingQuestionAdapter()
    }
    override fun createPresenter(): ExamContract.Presenter = ExamPresenter()

    override fun attachLayoutRes(): Int = R.layout.exam_paper

    override fun showLoading() {
        // swipeRefreshLayout.isRefreshing = isRefresh
    }

    override fun hideLoading() {
        //swipeRefreshLayout?.isRefreshing = false
    }

    override fun showError(errorMsg: String) {
        super.showError(errorMsg)
    }

    override fun initData() {
        handler.sendEmptyMessage(0)
        getToTime()
    }

    override fun initView() {
        super.initView()

        intent.extras?.let {
            pf_examSubjectId = it.getInt(Constant.EXAM_SUBJECT_ID_KEY, -1)
            tv_exam_paper_title.text = it.getString(Constant.EXAM_PAPER_NAME_KEY, "")
            tv_exam_paper_user_name.text = it.getString(Constant.EXAM_USER_NAME_KEY, "")

            val user_avatar=it.getString(Constant.EXAM_USER_AVATAR_KEY, "")
            if (user_avatar.isNotEmpty()) {
                ImageLoader.load(this, user_avatar, iv_exam_paper_user_avatar)
            } else {
                iv_exam_paper_user_avatar.setImageDrawable(resources.getDrawable(R.drawable.icon_default_user))
            }
        }

        rlv_single_answer.run {
            layoutManager = LinearLayoutManager(this@ExamActivity)
            adapter = singleAnswerAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(recyclerViewItemDecoration)
        }
        singleAnswerAdapter.run {
            bindToRecyclerView(rlv_single_answer)
        }
        rlv_multiple_answer.run {
            layoutManager = LinearLayoutManager(this@ExamActivity)
            adapter = multipleAnswerAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(recyclerViewItemDecoration)
        }
        multipleAnswerAdapter.run {
            bindToRecyclerView(rlv_multiple_answer)
        }
        rlv_true_false_question.run {
            layoutManager = LinearLayoutManager(this@ExamActivity)
            adapter = trueFalseQuestionAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(recyclerViewItemDecoration)
        }
        trueFalseQuestionAdapter.run {
            bindToRecyclerView(rlv_true_false_question)
        }
        rlv_blank_filling_question.run {
            layoutManager = LinearLayoutManager(this@ExamActivity)
            adapter = blankFillingQuestionAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(recyclerViewItemDecoration)
        }
        blankFillingQuestionAdapter.run {
            bindToRecyclerView(rlv_blank_filling_question)
        }
        btn_paper_save.setOnClickListener(onClickListener)
        btn_paper_submit.setOnClickListener(onClickListener)
        btn_paper_refresh.setOnClickListener(onClickListener)
    }

    /**
     * OnClickListener
     */
    private val onClickListener = View.OnClickListener { view ->
        when (view.id) {
            R.id.btn_paper_save -> {
                showToast("save")
            }
            R.id.btn_paper_refresh -> {
                showToast("refresh")
            }
            R.id.btn_paper_submit -> {
                showCircleDialog()
            }
        }
    }
    private fun showCircleDialog() {
        dialogFragment = CircleDialog.Builder() // .setTypeface(typeface)
               // .setTitle("提示")
                .setBodyView(R.layout.exam_dialog_customize) { viewHolder -> }
               // .setNegative("关闭", null)
                .show(supportFragmentManager)
    }

    override fun start() {
        mPresenter?.getSingleAnswerList(pf_examSubjectId )
        mPresenter?.getMultipleAnswerList(pf_examSubjectId )
        mPresenter?.getTrueFalseQuestionList(pf_examSubjectId)
        mPresenter?.getBlankFillingQuestionList(pf_examSubjectId)
    }

    override fun showSingleAnswerList(SingleAnswerList: List<SingleAnswer>) {
        SingleAnswerList.let {
            singleAnswerAdapter.run {
                addData(it)
            }
        }
    }

    override fun showMultipleAnswerList(MultipleAnswerList: List<MultipleAnswer>) {
        MultipleAnswerList.let {
            multipleAnswerAdapter.run{
                addData(it)
            }
        }
    }

    override fun showTrueFalseQuestionList(TrueFalseQuestionList: List<TrueFalseQuestion>) {
        TrueFalseQuestionList.let {
            trueFalseQuestionAdapter.run{
                addData(it)
            }
        }
    }

    override fun showBlankFillingQuestionList(BlankFillingQuestionList: List<BlankFillingQuestion>) {
        BlankFillingQuestionList.let {
            blankFillingQuestionAdapter.run{
                addData(it)
            }
        }
    }
    /**
     * RefreshListener
     */
    private val onRefreshListener = SwipeRefreshLayout.OnRefreshListener {
        mPresenter?.getSingleAnswerList(pf_examSubjectId)
    }
    /**
     * LoadMoreListener
     */
    //private val onRequestLoadMoreListener = BaseQuickAdapter.RequestLoadMoreListener {
   // }

    private val handler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            setTime()
            sendEmptyMessageDelayed(0, 1000)
        }
    }

    fun getToTime(){
        val df = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        val curDate = Date(System.currentTimeMillis())
        val format = df.format(curDate)
        val buffer = StringBuffer()
        val substring = format.substring(0, 11)
        buffer.append(substring)
        //Log.d("ymr", substring)
        val calendar = Calendar.getInstance()
        val hour = calendar[Calendar.HOUR_OF_DAY]
        buffer.append(hour)
        var minute=calendar[Calendar.MINUTE]
        buffer.append(":")
        minute=minute+1
        buffer.append(minute)
        buffer.append(":")
        val sec=calendar[Calendar.SECOND]
        buffer.append(sec)
        val totime = buffer.toString()
        //Log.d("totime", totime.toString())
        startTime_format=format
        endTime_format=totime
    }
    //秒杀倒计时
    fun setTime() {
        val df = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        val curDate = Date(System.currentTimeMillis())
        val currentDate_format = df.format(curDate)
        try {
            val endDate = df.parse(endTime_format)
            val currentDate = df.parse(currentDate_format)
            val defferenttime = endDate.time - currentDate.time
            val days = defferenttime / (1000 * 60 * 60 * 24)
            val hours =
                    (defferenttime - days * (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
            val minute =
                    (defferenttime - days * (1000 * 60 * 60 * 24) - hours * (1000 * 60 * 60)) / (1000 * 60)
            val seconds = defferenttime % 60000
            val second = Math.round(seconds.toFloat() / 1000).toLong()
            if (hours==0L) {
                tv_exam_paper_remaing_time_hour.setTextColor(resources.getColor(R.color.Red))
                if (minute<=1) {
                    tv_exam_paper_remaing_time_minute.setTextColor(resources.getColor(R.color.Yellow))
                    tv_exam_paper_remaing_time_second.setTextColor(resources.getColor(R.color.Yellow))
                    if (minute==0L){
                        tv_exam_paper_remaing_time_minute.setTextColor(resources.getColor(R.color.Red))
                        if (second<=10){
                            tv_exam_paper_remaing_time_second.setTextColor(resources.getColor(R.color.Red))
                        }
                    }
                }
            }
            tv_exam_paper_remaing_time_hour.text = "0$hours"
            if (minute >= 10) {
                tv_exam_paper_remaing_time_minute.text = minute.toString() + ""
            } else {
                tv_exam_paper_remaing_time_minute.text = "0$minute"
            }
            if (second >= 10) {
                tv_exam_paper_remaing_time_second.text = second.toString() + ""
            } else {
                tv_exam_paper_remaing_time_second.text = "0$second"
            }
        } catch (e: ParseException) {
            e.printStackTrace()
        }
    }
}